package cn.com.acca.ma.service.impl;

import java.awt.Color;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.RectangleInsets;

import cn.com.acca.ma.common.util.DateUtil;
import cn.com.acca.ma.common.util.PropertiesUtil;
import cn.com.acca.ma.model.Model;
import cn.com.acca.ma.model.ModelTopStock;
import cn.com.acca.ma.model.StockMovingAverage;
import cn.com.acca.ma.service.ModelTopStockService;

public class ModelTopStockServiceImpl extends BaseServiceImpl<ModelTopStockServiceImpl,Model> implements ModelTopStockService {
	
	/*********************************************************************************************************************
	 * 
	 * 												按日期计算数据
	 * 
	 *********************************************************************************************************************/
	/**
	 * 按照日期，向表MDL_TOP_STOCK中写入数据
	 * @param multithreading
	 */
	public void writeModelTopStock(boolean multithreading){
		String beginDate = PropertiesUtil.getValue(MODEL_TOP_STOCK_PROPERTIES, "top.stock.begin_date");
		String endDate = PropertiesUtil.getValue(MODEL_TOP_STOCK_PROPERTIES, "top.stock.end_date");
		Double numberPercentage = Double.parseDouble(PropertiesUtil.getValue(MODEL_TOP_STOCK_PROPERTIES, "top.stock.number.percentage"));
		modelTopStockDao.writeModelTopStock(multithreading, beginDate, endDate, numberPercentage);
	}
	
	/*********************************************************************************************************************
	 * 
	 * 												   	创建图表
	 * 
	 *********************************************************************************************************************/
	/**
	 * 创建龙头股票涨跌幅度图
	 */
	@SuppressWarnings({ "deprecation", "rawtypes" })
	public void createTopStockUpDownPicture(boolean multithreading){
		String topStockUpDownBeginDate = PropertiesUtil.getValue(MODEL_TOP_STOCK_PICTURE_PROPERTIES, "top.stock.picture.begin_date");
		String topStockUpDownEndDate = PropertiesUtil.getValue(MODEL_TOP_STOCK_PICTURE_PROPERTIES, "top.stock.picture.end_date");
		
		List stockMovingAverageList = stockTransactionDataDao.getAverageCloseWithDate(multithreading, topStockUpDownBeginDate, topStockUpDownEndDate, false, "all");
		List<ModelTopStock> modelTopStockList = modelTopStockDao.getModelTopStocks(multithreading, topStockUpDownBeginDate, topStockUpDownEndDate);
		
		TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection();
		TimeSeries stockMovingAverageTimeSeries= new TimeSeries("Average Close",org.jfree.data.time.Day.class);
		TimeSeries twentyOneTimeSeries = new TimeSeries("Twenty One Day Top Stock Up Down Average Percentage",org.jfree.data.time.Day.class);
		TimeSeries thirtyFourTimeSeries = new TimeSeries("Thirty Four Day Top Stock Up Down Average Percentage",org.jfree.data.time.Day.class);
		TimeSeries fiftyFiveTimeSeries = new TimeSeries("Fifty Five Day Top Stock Up Down Average Percentage",org.jfree.data.time.Day.class);
		TimeSeries eightyNineTimeSeries = new TimeSeries("Eighty Nine Day Top Stock Up Down Average Percentage",org.jfree.data.time.Day.class);
		TimeSeries oneHundredAndFortyFourTimeSeries = new TimeSeries("One Hundred And Forty Four One Top Stock Up Down Day Average Percentage",org.jfree.data.time.Day.class);
		TimeSeries twoHundredAndThirtyThreeTimeSeries = new TimeSeries("Two Hundred And Thirty Three One Top Stock Up Down Day Average Percentage",org.jfree.data.time.Day.class);
		TimeSeries threeHundredAndThirtySevenSeries = new TimeSeries("Three Hundred And Thirty Seven One Top Stock Up Down Day Average Percentage",org.jfree.data.time.Day.class);
		TimeSeries sixHundredAndTenSeries = new TimeSeries("Six Hundred And Ten One Top Stock Up Down Day Average Percentage",org.jfree.data.time.Day.class);
		
		for (int i = 0; i < stockMovingAverageList.size(); i++) {
			Object[] obj=(Object[])stockMovingAverageList.get(i);
			Date endDate=(Date) obj[0];
			int year=DateUtil.getYearFromDate(endDate);
			int month=DateUtil.getMonthFromDate(endDate);
			int date=DateUtil.getDateFromDate(endDate);
			
			if(obj[1]!=null){
				stockMovingAverageTimeSeries.add(new Day(date,month,year),(BigDecimal)obj[1]);
			}
		}
		
		for (int i = 0; i < modelTopStockList.size(); i++) {
			Date endDate=modelTopStockList.get(i).getDate();
			int year=DateUtil.getYearFromDate(endDate);
			int month=DateUtil.getMonthFromDate(endDate);
			int date=DateUtil.getDateFromDate(endDate);
			
			if(modelTopStockList.get(i).getTwentyOne()!=null){
				String[] twentyOneArray=modelTopStockList.get(i).getTwentyOne().split("\n");
				double sum=0;
				double avg=0;
				for(int j=0; j<twentyOneArray.length; j++){
					String[] stockArray=twentyOneArray[j].split("&");
					sum+=Double.parseDouble(stockArray[4]);
				}
				avg=sum/twentyOneArray.length;
				twentyOneTimeSeries.add(new Day(date,month,year),avg);
			}
			
//			if(modelTopStockList.get(i).getThirtyFour()!=null){
//				String[] thirtyFourArray=modelTopStockList.get(i).getThirtyFour().split("\n");
//				double sum=0;
//				double avg=0;
//				for(int j=0; j<thirtyFourArray.length; j++){
//					String[] stockArray=thirtyFourArray[j].split("&");
//					sum+=Double.parseDouble(stockArray[3]);
//				}
//				avg=sum/thirtyFourArray.length;
//				thirtyFourTimeSeries.add(new Day(date,month,year),avg);
//			}
//			
//			if(modelTopStockList.get(i).getFiftyFive()!=null){
//				String[] fiftyFiveArray=modelTopStockList.get(i).getFiftyFive().split("\n");
//				double sum=0;
//				double avg=0;
//				for(int j=0; j<fiftyFiveArray.length; j++){
//					String[] stockArray=fiftyFiveArray[j].split("&");
//					sum+=Double.parseDouble(stockArray[3]);
//				}
//				avg=sum/fiftyFiveArray.length;
//				fiftyFiveTimeSeries.add(new Day(date,month,year),avg);
//			}
//			
//			if(modelTopStockList.get(i).getEightyNine()!=null){
//				String[] eightyNineArray=modelTopStockList.get(i).getEightyNine().split("\n");
//				double sum=0;
//				double avg=0;
//				for(int j=0; j<eightyNineArray.length; j++){
//					String[] stockArray=eightyNineArray[j].split("&");
//					sum+=Double.parseDouble(stockArray[3]);
//				}
//				avg=sum/eightyNineArray.length;
//				eightyNineTimeSeries.add(new Day(date,month,year),avg);
//			}
//			
//			if(modelTopStockList.get(i).getOneHundredAndFortyFour()!=null){
//				String[] oneHundredAndFortyFourArray=modelTopStockList.get(i).getOneHundredAndFortyFour().split("\n");
//				double sum=0;
//				double avg=0;
//				for(int j=0; j<oneHundredAndFortyFourArray.length; j++){
//					String[] stockArray=oneHundredAndFortyFourArray[j].split("&");
//					sum+=Double.parseDouble(stockArray[3]);
//				}
//				avg=sum/oneHundredAndFortyFourArray.length;
//				oneHundredAndFortyFourTimeSeries.add(new Day(date,month,year),avg);
//			}
//			
//			if(modelTopStockList.get(i).getTwoHundredAndThirtyThree()!=null){
//				String[] twoHundredAndThirtyThreeArray=modelTopStockList.get(i).getTwoHundredAndThirtyThree().split("\n");
//				double sum=0;
//				double avg=0;
//				for(int j=0; j<twoHundredAndThirtyThreeArray.length; j++){
//					String[] stockArray=twoHundredAndThirtyThreeArray[j].split("&");
//					sum+=Double.parseDouble(stockArray[3]);
//				}
//				avg=sum/twoHundredAndThirtyThreeArray.length;
//				twoHundredAndThirtyThreeTimeSeries.add(new Day(date,month,year),avg);
//			}
//			
//			if(modelTopStockList.get(i).getThreeHundredAndThirtySeven()!=null){
//				String[] threeHundredAndThirtySevenArray=modelTopStockList.get(i).getThreeHundredAndThirtySeven().split("\n");
//				double sum=0;
//				double avg=0;
//				for(int j=0; j<threeHundredAndThirtySevenArray.length; j++){
//					String[] stockArray=threeHundredAndThirtySevenArray[j].split("&");
//					sum+=Double.parseDouble(stockArray[3]);
//				}
//				avg=sum/threeHundredAndThirtySevenArray.length;
//				threeHundredAndThirtySevenSeries.add(new Day(date,month,year),avg);
//			}
//			
//			if(modelTopStockList.get(i).getSixHundredAndTen()!=null){
//				String[] sixHundredAndTenArray=modelTopStockList.get(i).getSixHundredAndTen().split("\n");
//				double sum=0;
//				double avg=0;
//				for(int j=0; j<sixHundredAndTenArray.length; j++){
//					String[] stockArray=sixHundredAndTenArray[j].split("&");
//					sum+=Double.parseDouble(stockArray[3]);
//				}
//				avg=sum/sixHundredAndTenArray.length;
//				sixHundredAndTenSeries.add(new Day(date,month,year),avg);
//			}
		}
		timeSeriesCollection.addSeries(twentyOneTimeSeries);
		timeSeriesCollection.addSeries(stockMovingAverageTimeSeries);
//		timeSeriesCollection.addSeries(thirtyFourTimeSeries);
//		timeSeriesCollection.addSeries(fiftyFiveTimeSeries);
//		timeSeriesCollection.addSeries(eightyNineTimeSeries);
//		timeSeriesCollection.addSeries(oneHundredAndFortyFourTimeSeries);
//		timeSeriesCollection.addSeries(twoHundredAndThirtyThreeTimeSeries);
//		timeSeriesCollection.addSeries(threeHundredAndThirtySevenSeries);
//		timeSeriesCollection.addSeries(sixHundredAndTenSeries);
		
		JFreeChart jfreechart = ChartFactory.createTimeSeriesChart("Top Stock Up Down Percentage", 
				"Date","Up Down Percentage", timeSeriesCollection, true, true, true);
		jfreechart.setBackgroundPaint(Color.white);
		XYPlot xyplot = (XYPlot) jfreechart.getPlot();
		xyplot.setBackgroundPaint(Color.lightGray);
		xyplot.setDomainGridlinePaint(Color.white);
		xyplot.setRangeGridlinePaint(Color.white);
		xyplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));
		xyplot.setDomainCrosshairVisible(true);
		xyplot.setRangeCrosshairVisible(true);
		org.jfree.chart.renderer.xy.XYItemRenderer xyitemrenderer = xyplot.getRenderer();
		if (xyitemrenderer instanceof XYLineAndShapeRenderer) {
			XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyitemrenderer;
			xylineandshaperenderer.setBaseShapesVisible(true);
			xylineandshaperenderer.setBaseShapesFilled(true);
		}
		DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
		dateaxis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));

		try {
			FileOutputStream fos = new FileOutputStream(PICTURE_PATH+"top_stock_up_down/"+topStockUpDownBeginDate+"-"+topStockUpDownEndDate+PICTURE_FORMAT);
			// 将统计图标输出成JPG文件
			ChartUtilities.writeChartAsJPEG(fos, // 输出到哪个输出流
					1, // JPEG图片的质量，0~1之间
					jfreechart, // 统计图标对象
					imageWidth, // 宽
					IMAGE_HEIGHT, // 高
					null // ChartRenderingInfo 信息
					);
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("rawtypes")
	@Override
	public String listToString(List list) {
		// TODO Auto-generated method stub
		return null;
	}

}
